/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.utils;

import java.io.IOException;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * XML文件生成工具类
 * 
 * @author huangmy
 * @date   2007-12-24
 */
public class XmlWriteUtil {
	/**
	 * 获取一个空白的Document, 一般客户程序可以利用该Document进行XML文件的组装
	 * @return
	 */
	public static Document get() {
		return DocumentHelper.createDocument();
	}
	
	public static String create(Document document) throws Exception {
		return create(document, "UTF-8");
	}
	/**
	 * 
	 * @param document
	 * @return
	 * @throws Exception
	 */
	public static String create(Document document, String encoding) throws Exception {
		StringWriter strWriter = new StringWriter();
		OutputFormat format = OutputFormat.createPrettyPrint();		 
		format.setEncoding(encoding);	
		format.setTrimText(false);
		XMLWriter writer = new XMLWriter(strWriter,format);
		
		String xmlStr = null;
		try {
			writer.write(document);
			xmlStr = strWriter.toString();
		} catch (IOException e) {
			throw e;
		} finally {
			if (writer != null) {
			    writer.close();
			}
			
			if (strWriter != null) {
				strWriter.close();
			}
		}
        
		if (xmlStr != null) {
			xmlStr = XmlFileTrimUtil.trim(xmlStr);
		}

		return xmlStr;
	}

	/**
	 * 在一个指定的节点 root 下，添加子节点
	 * @param root
	 * @param name
	 * @param value
	 */
	public static Element addElement(Element root, String name, String value) {
		Element element = null;
		if (value == null) {
			element = root.addElement(name);
		} else {
			element = root.addElement(name).addText(value);
		}
		
		return element;
	}
	
	/**
	 * 在指定的节点下，添加新节点
	 * @param root
	 * @param name
	 * @return
	 */
	public static Element addElement(Element root, String name) {
		return addElement(root, name, null);
	}
}
